package com.itzhoun.aspectj;

import com.alibaba.fastjson.JSON;
import com.itzhoun.annotation.Log;
import com.itzhoun.async.AsyncManager;
import com.itzhoun.enums.BusinessStatus;
import com.itzhoun.enums.HttpMethod;
import com.itzhoun.createModel.factory.AsyncFactory;
import com.itzhoun.model.OpenerLog;
import com.itzhoun.utils.NetWorkIPUtils;
import com.itzhoun.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.Map;


/**
 * @author 周楠
 * @Date 2022/07/26/下午 9:42
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 配置植入点
     */
    @Pointcut("@annotation(com.itzhoun.annotation.Log)")
    public void logPointCut(){

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object result){

        try {
            Log annotationLog = getAnnotationLog(joinPoint);
            if (annotationLog == null) {
                return;
            }

            //获取当前查询的ip
            InetAddress ipAddress = NetWorkIPUtils.getIPAddress();
            OpenerLog openerLog = new OpenerLog();
            if (ipAddress != null){
                openerLog.setIp(ipAddress.getHostAddress());
            }
            //模块
            openerLog.setTitle(annotationLog.title());
            openerLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            openerLog.setJsonResult(JSON.toJSONString(result));
            openerLog.setUrl(ServletUtils.getRequest().getRequestURI());
            if (e != null){
                openerLog.setStatus(BusinessStatus.FAIL.ordinal());
                openerLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0 ,5000));
            }
            //设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            openerLog.setMethod(className + "." + methodName + "()");
            //设置请求方式
            openerLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            //处理设置注解上的参数
            getControllerMethodDescription(joinPoint,annotationLog, openerLog);

            AsyncManager.me().execute(AsyncFactory.recordOper(openerLog));
        }catch (Exception exp){
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }







    }

    /**
     * 获取注解
     * @param joinPoint
     * @return
     */
    private Log getAnnotationLog(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method == null){
            return null;
        }
        return method.getAnnotation(Log.class);
    }

    /**
     * 获取注解上的信息
     * @param joinPoint
     * @param log
     * @param openerLog
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OpenerLog openerLog){

        //获取业务类型
        openerLog.setBusinessType(log.businessType().ordinal());

        //获取标题
        openerLog.setTitle(log.title());

        //是否需要保存request
        if (log.isSaveRequestDate()){
            setRequestValue(joinPoint,openerLog);
        }
    }

    /**
     * 获取请求的参数放在log中
     * @param joinPoint
     * @param openerLog
     */
    private void setRequestValue(JoinPoint joinPoint, OpenerLog openerLog){
        //获取请求的参数
        String requestMethod = openerLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)){
            String s = argsArrayToString(joinPoint.getArgs());
            openerLog.setParam(StringUtils.substring(s,0 ,2000));
        }else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            openerLog.setParam(StringUtils.substring(paramsMap.toString(), 0 ,2000));
        }
    }

    /**
     * 参数拼接
     * @param paramsArray
     * @return
     */
    private String argsArrayToString(Object[] paramsArray){
        StringBuilder stringBuilder = new StringBuilder();
        for (Object o : paramsArray) {
            if (!isFilterObject(o)){
                Object o1 = JSON.toJSON(o);
                stringBuilder.append(o1.toString()).append(" ");
            }

        }
        return stringBuilder.toString().trim();

    }

    /**
     * 判断是否需要过滤对象
     * @param o
     * @return
     */
    private boolean isFilterObject(final Object o){

        return o instanceof MultipartFile ||
                o instanceof HttpServletRequest ||
                o instanceof HttpServletResponse;

    }






}
